const {
  // 创建ipc通信
  app,
  ipcMain,
  Menu,
  autoUpdater,
  dialog
} = require('electron')
const fs = require('fs');
require.extensions['.html'] = function(module, filename) {
  module.exports = fs.readFileSync(filename, 'utf8');
};

const template = [{
  label: '帮助',
  submenu: [{
    label: '检查更新',
    click() {
      checkForUpdates();
    }
  }]
}]



var queue = require('queue');
const log = require('electron-log');
const shell = require('electron').shell;


const Config = require('electron-config');
const config = new Config();
console.log(config.path);
var Handlebars = require('handlebars');
const XLSX = require('../lib/xlsx');
const mail = require('../lib/mail');

const MAIL_STATE = {
  RUNNING: 'running',
  PAUSE: 'pause',
  WARN: 'warn',
  SUCCESS: 'success',
  ERROR: 'error',
  WAITING: 'waiting'
};

//初始化完成后返回
ipcMain.on('ready-message', (event, arg) => {
  //添加菜单
  // if (process.platform === 'win32') {
  //   const menu = Menu.buildFromTemplate(template)
  //   Menu.setApplicationMenu(menu)
  // }

  let dbpath = XLSX.getDBPath();
  event.sender.send('ready-reply', fs.existsSync(dbpath))
})

//读取的excel
ipcMain.on('xlsxget-message', (event, arg) => {
  var query = {
    _state: {
      $ne: 'success'
    }
  }

  XLSX.get(query, (err, docs) => {
    event.sender.send('xlsxget-reply', {
      'cells': [],
      'data': docs
    })
  });
});

ipcMain.on('app-message', (event, arg) => {
  event.sender.send('app-reply', app.getVersion());
});


var q = queue({
  'concurrency': 1
});


ipcMain.on('open-file-dialog-message', (event, arg) => {
  dialog.showOpenDialog({
    title: '请选择工资表格',
    filters: [{
      name: 'xlsx',
      extensions: ['xls', 'xlsx']
    }],
    properties: ['openFile']
  }, function(files) {
    if (files) {
      var data = XLSX.read(files[0]);

      //如果有上次的数据，覆盖
      if (fs.existsSync(XLSX.getDBPath()))
        fs.unlinkSync(XLSX.getDBPath());

      XLSX.save(data, (err, newDoc) => {
        var keys = Object.keys(data[0]);

        var i = 0;

        var _cells = [];
        for (var i = 0; i < keys.length; i++) {
          let _used = getCellUsed(keys[i]);

          _cells[i] = {
            'name': keys[i],
            'used': _used
          };
        }

        //保存最新的。
        var smtpConfig = config.get('smtpConfig');
        smtpConfig.cells = _cells;
        config.set('smtpConfig', smtpConfig);

        event.sender.send('xlsxget-reply', {
          'cells': _cells,
          'data': newDoc
        });
      })
    }
  });
});

//获取config中的cell字段是否是使用的（used）
function getCellUsed(cellName) {
  var smtpConfig = config.get('smtpConfig');

  let _used = true;
  if (smtpConfig.cells) {
    for (var i = 0; i < smtpConfig.cells.length; i++) {
      let _cell = smtpConfig.cells[i];
      if (_cell.name === cellName) {
        _used = _cell.used;
        break;
      }
    }
  }

  return _used;
}


//上传excel
ipcMain.on('xlsxuplaod-message', (event, arg) => {});

//验证邮件配置
ipcMain.on('verifyConfiguration-message', (event, arg) => {
  mail.verifyConfiguration(arg, function(error) {
    event.sender.send('verifyConfiguration-reply', error);
  });
});

//发送邮件
ipcMain.on('sendmail-message', (event, arg) => {
  console.log("发送邮件：" + arg.subjectline);
  sendmailMessage(event, arg);
});



function sendmailMessage(event, arg) {
  XLSX.get((err, docs) => {
    if (err) {
      dialog.showErrorBox('错误提示', '加载数据有误' + err);
      return;
    }

    docs.forEach(function(employee) {
      employee.state = MAIL_STATE.WAITING;
      event.sender.send('update-state-reply', employee);
      q.push(function(done) {
        sendMail(employee, event, arg, done);
      });
    });

    q.start(function(err) {
      log.info('all done:');
      //event.sender.send('end-sendmail-reply', '');

      var query = {
        _state: {
          $ne: 'success'
        }
      }
      XLSX.get(query, (err, docs) => {
        let failSize = docs.length;
        let options = {
          title: '信息',
          buttons: ['OK'],
          message: '发送完成'
        };

        if (failSize === 0) {
          options.detail = '全部发送成功!';

          //清空数据
          if (fs.existsSync(XLSX.getDBPath()))
            fs.unlinkSync(XLSX.getDBPath());

          dialog.showMessageBox(options, function(optional) {
            if (optional === 0) {
              event.sender.send('sendmail-reply', docs);
              confirmQuit();
            }

          });
        } else {
          options.detail = `共${failSize}条发送失败，请点击重新发送`;
          options.buttons = ['重新发送', '取消'];

          log.warn('发送失败');
          dialog.showMessageBox(options, function(optional) {
            if (optional === 0) {
              sendmailMessage(event, arg);
            } else if (optional === 1) {
              event.sender.send('sendmail-reply', docs);
            }
          });
        }

      });
    });
  });
}

function confirmQuit() {
  let options = {
    title: '信息',
    message: '关闭应用',
    detail: '邮件都发送完毕，是否关闭应用？',
    buttons: ['关闭', '取消'],
  };
  dialog.showMessageBox(options, function(optional) {
    if (optional === 0) {
      app.quit();
    }
  });
}

function sendMail(employee, event, mailOptions, done) {
  if (!employee["邮箱"]) {
    log.warn('没有[邮箱]列');
    employee.state = MAIL_STATE.WARN;
    updateMailSate(employee, null);
    event.sender.send('update-state-reply', employee);
    //event.sender.send('progress-percentage-reply', 80);
    done();
    return;
  }
  console.log("subject111:" + mailOptions.subjectline);
  mail.sendMail(employee, mailOptions, function(error, info) {
    if (error) {
      log.error(`[error]:${error}`)
      employee.state = MAIL_STATE.ERROR;
    } else {
      employee.state = MAIL_STATE.SUCCESS;
    }

    updateMailSate(employee, function() {
      event.sender.send('update-state-reply', employee);
      //event.sender.send('progress-percentage-reply', 80);
      done();
    });
  });
}

function updateMailSate(employee, callback) {

  XLSX.update({
    _id: employee._id
  }, {
    $set: {
      _state: employee.state
    }
  }, {}, callback)
}


autoUpdater.on('update-available', function() {
  const options = {
    type: 'none',
    title: '检查更新',
    message: "发现有新版本，正在后台下载",
    buttons: ['OK']
  }

  dialog.showMessageBox(options, function() {

  });
})

autoUpdater.on('update-not-available', function() {
  const options = {
    type: 'none',
    title: '检查更新',
    message: "您当前已经是最新版！",
    buttons: ['OK']
  }

  dialog.showMessageBox(options, function() {

  });
})

autoUpdater.on('update-downloaded', function(event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
  const options = {
    type: 'none',
    title: '下载完毕',
    message: "下载完毕，正在安装并重新打开",
    buttons: ['OK']
  }

  dialog.showMessageBox(options);
  autoUpdater.quitAndInstall();
})

function checkForUpdates() {

  if (!fs.existsSync('squirrel.exe'))
    return;

  autoUpdater.setFeedURL('http://oo2log4xk.bkt.clouddn.com');
  autoUpdater.checkForUpdates();

  // fs.readdir('../', function(err, files) {
  //     if (err) {
  //         log.error(err);
  //         return;
  //     }
  //     var count = files.length;
  //     var results = {};
  //     files.forEach(function(filename) {
  //         if (filename.startsWith('app-') && filename !== `app-${app.getVersion()}`) {
  //             //删除老版本
  //             fs.rmdirAsync(`../${filename}`, function(err, stdout, stderr) {
  //                 if (err != null) {
  //                     console.log('clean build Folder error:' + err);
  //                     return;
  //                 }
  //             });
  //         }
  //     });
  // });
};
